import React, { useEffect, useState } from 'react';
import { Button, Card, Divider, Select, Table, Tag } from 'antd';
import { columns } from '../config/table.config.js';
import useGetData from '../useHook/useGetData';
import DatePickerComponent from './DatePicker';
import ModalComponent from './modal';

const Bill = () => {
    //更新数据
    const [flag_req, setFlagRequest] = useState(false);
    // 获取数据
    const [bill_data, categories_data] = useGetData('http://localhost:8088/1111', flag_req);
    // hash值转文字
    const [words, setWords] = useState({});
    // 筛选时间
    const [filterDate, setFilterDate] = useState({});
    // 账单数据管理
    const [new_bill_data, setBillData] = useState([]);
    const [new_categories_data, setCategoriesData] = useState([]);
    // 二次筛选原始数据
    const [secondData, setSecondData] = useState([]);
    // 是否展示二次筛选
    const [secondBool, setSecondBool] = useState(false);
    // 二次筛选条件
    const [secondFind, setSecondFind] = useState(null);
    // 弹框管理
    const [modalStatus, setModalStatus] = useState(false);
    // 收入金额
    const [income, setIncome] = useState(0);
    //支出金额
    const [expenditure, setExpenditure] = useState(0);

    useEffect(() => {
        setBillData(bill_data);

        const [_income, _expenditure] = momeny(bill_data);

        setIncome(_income);
        setExpenditure(_expenditure);
    }, [bill_data]);

    useEffect(() => {
        const wordsObj = {};
        for (let T of categories_data) {
            wordsObj[T.id] = T.name;
        };

        setWords(wordsObj);
        setCategoriesData(categories_data);
    }, [categories_data])

    useEffect(() => {
        if (
            Object.keys(filterDate).length &&
            bill_data.length
        ) {
            let newA = bill_data.filter(
                item =>
                    parseInt(item.time) < filterDate.end &&
                    parseInt(item.time) >= filterDate.start
            );

            const [_income, _expenditure] = momeny(newA);

            setBillData(newA);
            setSecondData(newA);
            setIncome(_income);
            setExpenditure(_expenditure);

            //切换日期 清空选择的分类
            if (secondFind) setSecondFind(null);
        }
    }, [filterDate, bill_data]);

    // 计算支出和收入
    const momeny = (arr) => {
        let _income = 0, _expenditure = 0;

        for (let T of arr) {
            if (T.type === '1') {
                _income += parseInt(T.amount);
            } else {
                _expenditure += parseInt(T.amount);
            }
        };

        return [_income, _expenditure];
    };

    const selectComponent = () => {
        return new_categories_data.map(item => {
            return <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
        })
    };

    /**
     *
     * @param {id} e
     */
    const onSelect = (e) => {

        // 二次分类排序
        const newA = secondData
            .filter(item => item.category === e)
            .sort(_sort);

        const [_income, _expenditure] = momeny(newA);

        setSecondFind(e)
        setBillData(newA);
        setIncome(_income);
        setExpenditure(_expenditure);
    };

    const select_onChange = (e) => e || setBillData(secondData);

    const _sort = (a, b) => parseInt(b.amount) - parseInt(a.amount);

    const view = () => (
        <div>
            <DatePickerComponent dateCallback={setFilterDate} setSecondBool={setSecondBool} />
            <Divider type='vertical' dashed />
            {secondBool && <>
                <Select
                    onSelect={onSelect}
                    style={{ width: 150 }}
                    placeholder='选择详细类别'
                    allowClear
                    onChange={select_onChange}
                    value={secondFind}
                >
                    {selectComponent()}
                </Select>
                <Divider type='vertical' dashed />
            </>
            }
            <br />
            <Divider type='horizontal' dashed />
            <Button
                type='primary'
                ghost
                onClick={() => setModalStatus(true)}
            >添加</Button>

            <ModalComponent
                modalStatus={modalStatus}
                setModalStatus={setModalStatus}
                setFlagRequest={setFlagRequest}
                categories_data={categories_data}
            />
        </div>
    );

    const titleView = () => (
        <div>
            <span>账单</span>
            <Divider type='vertical' dashed />
            <span>
                支出：
                <Tag color='orange'>{expenditure}</Tag>
            </span>
            <Divider type='vertical' dashed />
            <span>
                收入：
                <Tag color='geekblue'>{income}</Tag>
            </span>
        </div>
    )

    return (
        <Card
            title={titleView()}
            extra={view()}
            size='small'
            bordered={false}
        >
            <Table
                columns={columns(words)}
                dataSource={new_bill_data}
                pagination={false}
                size='small'
            />
        </Card>
    )
};

export default Bill;